package com.jiuyou.storeController.finance;

import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.util.AdapaySign;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.adapayBalance.service.IAdapayBalanceService;
import com.ruoyi.adapayBalanceRecord.domain.AdapayBalanceRecord;
import com.ruoyi.adapayBalanceRecord.service.IAdapayBalanceRecordService;
import com.ruoyi.adapayDrawcash.domain.AdapayDrawcash;
import com.ruoyi.adapayDrawcash.service.IAdapayDrawcashService;
import com.ruoyi.clerkBalance.service.IClerkBalanceService;
import com.ruoyi.clerkBalanceRecord.domain.ClerkBalanceRecord;
import com.ruoyi.clerkBalanceRecord.service.IClerkBalanceRecordService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.storeUser.service.IStoreUserService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 *
 */
@RestController
@RequestMapping("/store/finance")
@Api(tags = {"财务流水"})

public class FinanceStoreController extends StoreBaseController {
    private static final Logger log = LoggerFactory.getLogger(FinanceStoreController.class);
    @Autowired
    private IAdapayDrawcashService adapayDrawcashService;
    @Autowired
    private IAdapayBalanceRecordService adapayBalanceRecordService;
    @Autowired
    private IAdapayBalanceService adapayBalanceService;
    @Autowired
    private IStoreUserService storeUserService;
    @Autowired
    private IClerkBalanceService clerkBalanceService;
    @Autowired
    private IClerkBalanceRecordService clerkBalanceRecordService;
    /**
     * 申请提现（新加的，员工）
     * */
    @PostMapping("/applyStaffDrawcash")
    public AjaxResult applyStaffDrawcash()  {
        Long  loginStoreUserId= getLoginStoreUserId();
        if(null==loginStoreUserId){
            return AjaxResult.error("重新进入小程序后再试");
        }
//        StoreUserRole storeUserRole=getStoreUserRole();
//        Long storeId= storeUserRole.getStoreId();
        StoreUser storeUser= storeUserService.selectStoreUserById(loginStoreUserId);
        Long storeId = storeUser.getStoreId();
        return adapayDrawcashService.applyStaffDrawcash(storeId,loginStoreUserId);
    }

    /**
     * 申请提现（原有的，门店）
     * @return
     */
    @PostMapping("/applyDrawcash")
    public AjaxResult applyDrawcash()  {
        Long  loginStoreUserId= getLoginStoreUserId();
        if(null==loginStoreUserId){
            return AjaxResult.error("重新进入小程序后再试");
        }
        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        return adapayDrawcashService.applyDrawcash(storeId,loginStoreUserId);
    }
    /**
     * 提现支付回调
     * @param request
     */
    @RequestMapping("/drawcashNotify")
    public void refundPayNotify(HttpServletRequest request) {
        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");
            //验签标记
            boolean checkSign;
            //验签请参publicKey
            String publicKey = AdapayCore.PUBLIC_KEY;
            log.info("验签请参：data={}sign={}");
            //验签
            checkSign = AdapaySign.verifySign(data, sign, publicKey);
            if(checkSign){
                //验签成功逻辑
                System.out.println("drawcashNotify成功返回数据退款回调data:"+data);
                JSONObject dataJson= JSONObject.parseObject(data);
                String order_no=dataJson.getString("order_no");//交易订单号？

                AdapayDrawcash adapayDrawcashQuery=new AdapayDrawcash();
                adapayDrawcashQuery.setOrderNo(order_no);
                List<AdapayDrawcash> listdr=     adapayDrawcashService.selectAdapayDrawcashList(adapayDrawcashQuery);
                if(listdr.size()>0){
                    AdapayDrawcash adapayDrawcash=listdr.get(0);
                    String drawcashState=  adapayDrawcash.getDrawcashState();
                    if("succeeded".equals(drawcashState)){
                        //已经处理过
                        return;
                    }

                    AdapayDrawcash adapayDrawcashUpdate=new AdapayDrawcash();
                    adapayDrawcashUpdate.setId(adapayDrawcash.getId());
                    String status=dataJson.getString("status");
                    adapayDrawcashUpdate.setDrawcashState(status);
                    if("succeeded".equals(status)){
                        //退款成功

                    }
                    if("failed".equals(status)){
                        //交易失败
                    }
                    adapayDrawcashUpdate.setUpdateTime(new Date());
                    adapayDrawcashUpdate.setNotifyParam(data);
                    adapayDrawcashService.updateAdapayDrawcash(adapayDrawcashUpdate);
                }

            }else {
                //验签失败逻辑
            }
        }catch (Exception e){
            log.info("异步回调开始，参数，request={}");
        }
        return ;
    }
    /**
     * 提现记录
     * @return
     */
    @PostMapping("/listDrawcashRecord")
    public TableDataInfo listDrawcashRecord()
    {
//        StoreUserRole storeUserRole=getStoreUserRole();
//        Long storeId= storeUserRole.getStoreId();
        Long  loginStoreUserId= getLoginStoreUserId();
        StoreUser storeUser= storeUserService.selectStoreUserById(loginStoreUserId);
        Long storeId = storeUser.getStoreId();

        AdapayDrawcash adapayDrawcash=new AdapayDrawcash();
        adapayDrawcash.setStoreId(storeId);
        adapayDrawcash.setStoreUserId(loginStoreUserId);
        startPage();
        List<AdapayDrawcash> list = adapayDrawcashService.selectAdapayDrawcashList(adapayDrawcash);
        return getDataTable(list);
    }
    /**
     * 查询余额流水列表
     */
    @PostMapping("/listBalanceRecord")
    public TableDataInfo listBalanceRecord(String recodeDate){
        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        AdapayBalanceRecord adapayBalanceRecord=new AdapayBalanceRecord();
        adapayBalanceRecord.setStoreId(storeId);
        adapayBalanceRecord.getParams().put("recodeDate",recodeDate);
        startPage();
        List<AdapayBalanceRecord> list = adapayBalanceRecordService.selectAdapayBalanceRecordList(adapayBalanceRecord);
        return getDataTable(list);
    }
    /**
     * 查询余额流水列表
     */
    @PostMapping("/getBalance")
    public AjaxResult getBalance(){
        Long  loginStoreUserId= getLoginStoreUserId();
        if(null==loginStoreUserId){
            return AjaxResult.error("重新进入小程序后再试");
        }
        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        return AjaxResult.success( adapayBalanceService.getAdapayBalanceByStoreId(storeId))  ;
    }
    /**
     * 支付付款回调
     * @param request
     */
    @RequestMapping("/notify")
    public void notify(HttpServletRequest request) {
        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");
            //验签标记
            boolean checkSign;
            //验签请参publicKey
            String publicKey = AdapayCore.PUBLIC_KEY;
            log.info("验签请参：data={}sign={}");
            //验签
            checkSign = AdapaySign.verifySign(data, sign, publicKey);
            if(checkSign){
                //验签成功逻辑
                System.out.println("成功返回数据data:"+data);
                JSONObject dataJson= JSONObject.parseObject(data);
                // pending 交易处理中 succeeded 交易成功 failed失败

                String order_no=dataJson.getString("order_no");//交易订单号？wx开头加时间戳
                String status=dataJson.getString("status");
                    if("succeeded".equals(status)){
                        //交易成功

                    }
                    if("failed".equals(status)){
                        //交易失败
                    }

            }else {
                //验签失败逻辑
            }
        }catch (Exception e){
            log.info("异步回调开始，参数，request={}");
        }
        return ;
    }


    /**
     * 查询余额流水列表(员工端)
     */
    @PostMapping("/getClerkBalance")
    public AjaxResult getClerkBalance(){
        Long  loginStoreUserId= getLoginStoreUserId();
        if(null==loginStoreUserId){
            return AjaxResult.error("重新进入小程序后再试");
        }
//        StoreUserRole storeUserRole=getStoreUserRole();
//        Long storeId= storeUserRole.getStoreId();
        return AjaxResult.success( clerkBalanceService.getClerkBalanceByStoreUserId(loginStoreUserId))  ;
    }

    /**
     * 提现记录(员工端)
     * @return
     */
    @PostMapping("/listClerkDrawcashRecord")
    public TableDataInfo listClerkDrawcashRecord()
    {
//        StoreUserRole storeUserRole=getStoreUserRole();
//        Long storeId= storeUserRole.getStoreId();
        Long  loginStoreUserId= getLoginStoreUserId();
        StoreUser storeUser= storeUserService.selectStoreUserById(loginStoreUserId);
        Long storeId = storeUser.getStoreId();

        AdapayDrawcash adapayDrawcash=new AdapayDrawcash();
        adapayDrawcash.setStoreId(storeId);
        adapayDrawcash.setStoreUserId(loginStoreUserId);
        startPage();
        List<AdapayDrawcash> list = adapayDrawcashService.selectAdapayDrawcashList(adapayDrawcash);
        return getDataTable(list);
    }

    /**
     * 查询余额流水列表(员工端)
     */
    @PostMapping("/listClerkBalanceRecord")
    public TableDataInfo listClerkBalanceRecord(String recodeDate){
//        StoreUserRole storeUserRole=getStoreUserRole();
//        Long storeId= storeUserRole.getStoreId();

        Long  loginStoreUserId= getLoginStoreUserId();
        StoreUser storeUser= storeUserService.selectStoreUserById(loginStoreUserId);
        Long storeId = storeUser.getStoreId();

//        AdapayBalanceRecord adapayBalanceRecord=new AdapayBalanceRecord();
//        adapayBalanceRecord.setStoreId(storeId);
//        adapayBalanceRecord.getParams().put("recodeDate",recodeDate);

        ClerkBalanceRecord clerkBalanceRecord = new ClerkBalanceRecord();
        clerkBalanceRecord.setStoreId(storeId);
        clerkBalanceRecord.setStoreUserId(loginStoreUserId);
        clerkBalanceRecord.getParams().put("recodeDate",recodeDate);
        startPage();
        List<ClerkBalanceRecord> list = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord);
        return getDataTable(list);
    }

}
